use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Output<T> {
    pub status_code: u16,
    pub message: String,
    pub data: Option<T>,
}

impl<T> Output<T> {
    pub fn success(message: String, data: Option<T>) -> Self {
        Output {
            status_code: 200,
            message,
            data,
        }
    }

    pub fn failure(status_code: u16, message: String) -> Self {
        Output {
            status_code,
            message,
            data: None,
        }
    }
}

impl<T: Serialize> IntoResponse for Output<T> {
    fn into_response(self) -> Response {
        let status_code = StatusCode::from_u16(self.status_code as u16)
            .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
        // 使用 Json 来序列化 self，然后与状态码一起返回
        (status_code, axum::Json(self)).into_response()
    }
}
